//  app/utils/fileHandle.js
const { app } = require('electron');
const path = require('path');
const fsPromises = require('fs').promises; // 使用 fs.promises 来获取 Promise 版本的函数
const fs = require('fs'); // 使用 fs.promises 来获取 Promise 版本的函数

const logger = require('@utils/logger');
const { isDev } = require('@utils/helper');
const nettools = require('@utils/network');
const gs = require('@utils/globalStore');


const resourceRoot = 'uploads';

function getloadUrl() {
    
    console.log(`isDev::${isDev()} clientPort::${gs.getClientPort()}`);

    return isDev()
        ? `http://localhost:${gs.getClientPort()}/`
        : `http://${nettools.getLocalIP()}:${gs.getServerPort()}/`;
}

// 动态获取 preload.js 的路径
function getPreloadPath() {

    let preloadPath;

    preloadPath = isDev()
        ? path.resolve(app.getAppPath(), 'renderer', 'preload.js')
        : path.join(process.resourcesPath, 'renderer/preload.js');

    logger.info(`[+10002] 〖ISDEV:${isDev()}〗:: dynamic get 【preload path】::${preloadPath}`);

    return preloadPath;

}

// 获取userData目录
function getUserDataPath(toPath = '') {

    const userDataPath = app.getPath('userData');
    const dispath = path.join(userDataPath, toPath);

    // 确保 toPath 目录存在
    if (!fs.existsSync(dispath)) {
        fs.mkdirSync(dispath, { recursive: true });
    }
    return dispath;
}

// 资源服务器root
function getResourceRoot() {
    return getUserDataPath(resourceRoot);
}

// 资源服务器root
function getDBPath() {
    let dbPath = ''

    const config = gs.get('config')

    if (config != undefined && config['DATABASE'] != undefined && config['DATABASE']['path'] && config['DATABASE']['dbname']) {
        dbPath = path.join(getUserDataPath(config['DATABASE']['path']), config['DATABASE']['dbname']);
    } else {
        dbPath = path.join(getUserDataPath('dbs'), 'task.esv2');
    }

    // 检查并创建数据库文件
    if (!fs.existsSync(dbPath)) {
        logger.info('[+00004]Database file does not exist. Creating a new one...');
        fs.writeFileSync(dbPath, ''); // 创建一个空的数据库文件
    }
    return dbPath
}

// 资源服务器项目目录
function getProjectPath() {
    const root = getResourceRoot();
    const dispath = path.join(root, projectPath);

    if (!fs.existsSync(dispath)) {
        fs.mkdirSync(dispath, { recursive: true });
    }

    return dispath;
}

// 资源服务器素材目录
function getUserSignUploadPath() {
    const root = getResourceRoot();
    const dispath = path.join(root, resourceRoot);

    if (!fs.existsSync(dispath)) {
        fs.mkdirSync(dispath, { recursive: true });
    }

    return dispath;
}

// 获取 client-dist 目录的路径
function getClientDistPath() {
    let clientRoot = '';

    clientRoot = process.env.NODE_ENV == 'development' ? path.join(app.getAppPath(), 'dist') : path.join(process.resourcesPath, 'dist');

    logger.warn('[+10003] client server root path in funtion getClientDistPath::', clientRoot);

    return clientRoot;
}

// 递归读取目录
async function readDirRecursively(dirPath, filterConfig) {
    const result = [];
    try {
        const files = await fsPromises.readdir(dirPath, { withFileTypes: true });
        for (const file of files) {
            const fullPath = path.join(dirPath, file.name);
            if (file.isDirectory()) {
                if (isIncluded(file.name, 'directory', filterConfig)) {
                    const children = await readDirRecursively(fullPath, filterConfig);
                    result.push({
                        type: 'directory',
                        name: file.name,
                        children: children,
                    });
                }
            } else if (file.isFile()) {
                if (isIncluded(file.name, 'file', filterConfig)) {
                    result.push({ type: 'file', name: file.name });
                }
            }
        }
    } catch (error) {
        logger.error(`[+10014]Error reading directory ${dirPath}:`, error);
        throw error;
    }
    return result;
}

function isIncluded(name, type, filterConfig) {
    const config = filterConfig.find(cfg => cfg.type === type);
    if (!config) return true; // 如果没有配置，默认包含

    // 如果在 include 列表中，直接包含
    if (config.include.includes(name)) {
        return true;
    }
    // 如果在 exclude 列表中，直接排除
    if (config.exclude.includes(name)) {
        return false;
    }
    // 如果 include 列表不为空，且不在 include 列表中，排除
    // if (config.include.length > 0) {
    //     return false;
    // }
    // 默认包含
    return true;
}

const uploadImage = (base64Data) => {
    const matches = base64Data.match(/^data:image\/([A-Za-z-+\/]+);base64,(.+)$/);
    if (!matches || matches.length !== 3) {
        throw new Error('Invalid base64 image data');
    }

    const imageType = matches[1];
    const imageData = matches[2];
    const buffer = Buffer.from(imageData, 'base64');

    const userDataPath = app.getPath('userData');
    const mediaPath = path.join(userDataPath, 'media');
    const date = new Date();
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const timestamp = date.toISOString().replace(/[-:.]/g, '').slice(0, 14);
    const fileName = `${timestamp}_decoded_image.${imageType}`;
    const filePath = path.join(mediaPath, year.toString(), month, day, fileName);
    const relationPath = `${year.toString()}/${month}/${day}/${fileName}`

    if (!fs.existsSync(path.dirname(filePath))) {
        fs.mkdirSync(path.dirname(filePath), { recursive: true });
    }

    fs.writeFileSync(filePath, buffer);

    return relationPath;
};

module.exports = {
    readDirRecursively,
    getClientDistPath,
    getDBPath,
    getUserDataPath,
    getPreloadPath,
    getProjectPath,
    getResourceRoot,
    getUserSignUploadPath,
    uploadImage,
    getloadUrl
};